package com.cap.bts.crmdp.dealer.remind.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cap.bts.commonfunc.common.util.DateUtil;
import com.cap.bts.crmdp.commons.sftp.SFTPProcessor;
import com.cap.bts.crmdp.commons.sftp.SftpProperties;
import com.cap.bts.crmdp.dealer.masterinfo.constants.MasterInfoConstants;
import com.cap.bts.crmdp.dealer.masterinfo.domain.MasterFileModel;
import com.cap.bts.crmdp.dealer.masterinfo.dto.MaeterInfoDto;
import com.cap.bts.crmdp.dealer.masterinfo.dto.MasterFileDto;
import com.cap.bts.crmdp.dealer.masterinfo.service.IMasterInfoService;
import com.cap.bts.crmdp.dealer.masterinfo.utils.MasterInfoUtils;
import com.cap.bts.crmdp.httpconnection.HttpConnectionUtils;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.controller.BaseController;
import com.cap.bts.framework.common.exception.AppException;
import com.jcraft.jsch.ChannelSftp;

@Controller
@RequestMapping(value = "/crmdp/dealer/remind")
public class RemindSyncController extends BaseController {

//    private static final Logger LOGGER = Logger.getLogger(RemindSyncController.class);

    @Autowired
    IMasterInfoService          iMasterInfoService;

    @Autowired
    ICodeMapping                iCodeMapping;

    /**
     * 同步数据页面初始化
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     */
    @RequestMapping(value = "toSyncRemindData")
    public String toSyncRemindData(Model model)
                                                                                           throws AppException {

        //根据类型查询出所有的文件类型
        List<CodeInfo> masterInfoTypeList = iCodeMapping
            .getCodeInfoByType(MasterInfoConstants.MASTER_INFO_FILETYPE);

        model.addAttribute("masterInfoTypeList", masterInfoTypeList);
        return "/remind/syncRemind";
    }
/*
    *//**
     * 页面操作调用的同步方法
     * @param dto
     * @param model
     * @param request
     * @return
     * @throws AppException
     *//*
    @RequestMapping(value = "/tongbushuju")
    @ResponseBody
    public Map<String, Object> tongbushuju(MaeterInfoDto dto, HttpServletRequest request) throws AppException {

        SftpProperties sftpProperties = new SftpProperties("mccrm-dpweb-uat.chinacloudapp.cn", "sftpcrm", "Ie(&%IUh_", 52222);

        SFTPProcessor ftpUtil = new SFTPProcessor();
        ChannelSftp channelSftp = ftpUtil.getConnect(sftpProperties);

        if(channelSftp.isConnected()){
            ftpUtil.downloadFile("12345678.txt", "/upload", "d:/123.txt");
        }

        try {
            ftpUtil.closeChannel();
        } catch (Exception e) {
        	LOGGER.error("tongbushuju",e);
        }
        
       
        String fileType = request.getParameter("fileType");
        Map<String, Object> jsonMap = new HashMap<String, Object>();

        //根据code查询出查询文件的地址
        CodeInfo codeInfo = iCodeMapping
            .getCodeInfoByCode(MasterInfoConstants.MASTER_INFO_QUERY_FILEPATH);
        String urlPath = null;
        if (codeInfo != null) {
            urlPath = codeInfo.getValue();
        } else {
            LOGGER.error("文件查询地址获取失败：urlPath=" + urlPath);
            jsonMap.put("code", false);
            jsonMap.put("msg", "文件地址获取失败");
            return jsonMap;
        }
        String charset = "UTF-8";
        int connectTimeout = 6000;
        int readTimeout = 6000;
        urlPath += "fileType=" + fileType;
        try {
            String result = HttpConnectionUtils.openHttpsConnection(urlPath, charset,
                connectTimeout, readTimeout, null);
            LOGGER.info("获取到的文件信息：" + result);

            //获得同步的方法
            String synchronizationMethod = dto.getSynchronizationMethod();

            Map<String, Object> dataMap = getFileInfo(result, fileType, synchronizationMethod);
            saveInfo(dataMap, dto);
            jsonMap.put("code", true);
            jsonMap.put("msg", "同步成功");
            return jsonMap;
        } catch (Exception e) {
            LOGGER.error("提取信息失败", e);
            jsonMap.put("code", false);
            jsonMap.put("msg", "同步失败");
            return jsonMap;
        }
    }

    *//**
     * 定时任务调用的同步方法
     * @param dto
     * @param model
     * @param request
     * @throws AppException
     *//*
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/getOpenHttpConnect")
    public void getOpenHttpConnect(MaeterInfoDto dto)
                                                                                              throws AppException {
        //根据code查询出查询文件的地址
        CodeInfo codeInfo = iCodeMapping
            .getCodeInfoByCode(MasterInfoConstants.MASTER_INFO_QUERY_FILEPATH);
        String urlPath;
        if (codeInfo != null) {
            urlPath = codeInfo.getValue();
        } else {
            throw new AppException("error", "文件查询地址获取失败");
        }
        String charset = "UTF-8";
        int connectTimeout = 6000;
        int readTimeout = 6000;
        urlPath += "fileType=" + dto.getFileType();
        try {
            String result = HttpConnectionUtils.openHttpsConnection(urlPath, charset,
                connectTimeout, readTimeout, null);
            LOGGER.info("获取到的文件信息：" + result);

            
            List<CodeInfo> masterInfoTypeList = iCodeMapping
                .getCodeInfoByType(MasterInfoConstants.MASTER_INFO_FILETYPE);
            for (Iterator iterator = masterInfoTypeList.iterator(); iterator.hasNext();) {
                CodeInfo codeInfo2 = (CodeInfo) iterator.next();
                Map<String, Object> resultMap = getFileInfo(result, codeInfo2.getType(),
                    MasterInfoConstants.SYNCHRONIZATIONMETHOD_INCREMENT);
                saveInfo(resultMap, dto);
            }
        } catch (Exception e) {
            LOGGER.error("提取信息失败", e);

        }

    }

    *//**
     * 解析数据
     * @param result
     * @return
     * @throws Exception 
     *//*
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map<String, Object> getFileInfo(String result, String fileType,
                                           String synchronizationMethod) throws AppException{
        JSONObject jsonObject = JSONObject.parseObject(result);
        String status = jsonObject.getString("status");
        String message = jsonObject.getString("message");
        Map<String, Object> dataMap = null;
        
        List<Map<String, Object>> resultList = new ArrayList();
        if ("200".equals(status) && "ok".equals(message)) {
            String dataString = jsonObject.getString("data");

            JSONArray jsonArray = JSONArray.parseArray(dataString);

            String currentDte = DateUtil.getDateText(new Date());
            //本地存储目录
            String localFilePath = MasterInfoConstants.getLOCALHOSTPATH_STRING() + fileType + "/"
                                   + currentDte + "/";

            int num = 0;
            dataMap = new HashMap<String, Object>();
            for (Iterator iterator = jsonArray.iterator(); iterator.hasNext();) {
                JSONObject object = (JSONObject) iterator.next();
                String fileName = object.getString("fileName");//获取文件下载的名称
                String fileUrl = object.getString("fileUrl");//获取文件下载的地址

                //增量同步Master数据
                if (MasterInfoConstants.SYNCHRONIZATIONMETHOD_INCREMENT
                    .equals(synchronizationMethod)) {
                    //判断该文件是否已经被同步过
                    MasterFileDto masterFileDto = new MasterFileDto();
                    masterFileDto.setFileName(fileName);
                    MasterFileModel masterFileModel = iMasterInfoService
                        .getMasterFileInfoByFileName(masterFileDto);

                    if (masterFileModel != null) {
                        continue;
                    }
                }
                fileName = fileName.substring(0, fileName.indexOf(".csv"));

                //根据code查询出需要文件下载的URL地址
                CodeInfo codeInfo = iCodeMapping
                    .getCodeInfoByCode(MasterInfoConstants.MASTER_INFO_DOWNLOAD_FILEPATH);

                String urlPath = null;
                if (codeInfo != null) {
                    urlPath = codeInfo.getValue() + fileUrl;
                }
                File csvFile = null;
                if (urlPath != null && localFilePath != null && fileName != null) {
                    try {
                        csvFile = HttpConnectionUtils.downloadFile(urlPath, localFilePath, fileName);
                    } catch (IOException e) {
                        throw new AppException("getFileInfo", e);
                    }
                }
                List<String> list = MasterInfoUtils.analyzeCsv(csvFile);
                List<Map<String, Object>> dataList = MasterInfoUtils.combinationList(list);
                dataMap.put("dataList" + num, dataList);
                
                Map<String, Object> fileNameMap = new HashMap<String, Object>();
                fileNameMap.put("fileName", fileName + ".csv");
                resultList.add(num, fileNameMap);
                
                num++;
            }

        }

        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("data", dataMap);
        resultMap.put("fileNameList", resultList);

        return resultMap;
    }

    *//**
     * 保存数据
     * @param dataMap
     * @throws Exception
     *//*
    public void saveInfo(Map<String, Object> resultMap, MaeterInfoDto dto) throws AppException{
        iMasterInfoService.checkSaveInfo(resultMap, dto);
    }*/
}
